
from http import HTTPStatus
from dotenv import load_dotenv
import os
DASHSCOPE_IMPORT_SUCCESS = False

env_path = os.path.join(os.path.dirname(__file__), ".env")

have_dashscope_key = load_dotenv(env_path)

if not have_dashscope_key or not os.getenv("DASHSCOPE_API_KEY"):
    print("You need to have a .env file with DASHSCOPE")
    print("API_KEY=your_api_key")
else:
    print("You have a .env file with DASHSCOPE API_KEY")
    try:
        import dashscope
        DASHSCOPE_IMPORT_SUCCESS = True
    except ImportError as e:
        print("Failed to import dashscope module:", e)
if DASHSCOPE_IMPORT_SUCCESS:
    print("Dashscope module imported successfully!")
else:
    print("Failed to import dashscope module.")


def CorrectEnglishSyntaxAndSpelling(origin):
    messages = [
        {"role": "system", "content": "You are a grammar corrector. Give you some English sentences to fix grammar and spelling errors. Your responses should only include translated statements."},
        {"role": "user", "content": origin}
    ]
    response = dashscope.Generation.call(
        model=dashscope.Generation.Models.qwen_turbo,
        messages=messages
    )
    is_success = response.status_code == HTTPStatus.OK
    # The response status_code is HTTPStatus.OK indicate success,
    # otherwise indicate request is failed, you can get error code
    # and message from code and message.
    if response.status_code == HTTPStatus.OK:
        print(response.output)  # The output text
        print(response.usage)  # The usage information
        result = response.output["text"]
        if result[0] == "\"" and result[-1] == "\"":
            result = result[1:-1]
        if result[0] == "'" and result[-1] == "'":
            result = result[1:-1]
        return is_success, result

    else:
        print(response.code)  # The error code.
        print(response.message)  # The error message.
        return is_success, response.message


def AnalysisResults(failure_results):
    results = ""
    for i, result in enumerate(failure_results):
        results += f"{i+1}. {result}\n"
    messages = [
        {"role": "system", "content": "I am a results analyst. Provide me with some experimental results, and I will help summarize the reasons for failure. Your response should be in LaTeX format."},
        {"role": "user", "content": results}
    ]
    response = dashscope.Generation.call(
        model=dashscope.Generation.Models.qwen_turbo,
        messages=messages
    )

    is_success = response.status_code == HTTPStatus.OK
    # The response status_code is HTTPStatus.OK indicate success,
    # otherwise indicate request is failed, you can get error code
    # and message from code and message.
    if response.status_code == HTTPStatus.OK:
        print(response.output)  # The output text
        print(response.usage)  # The usage information
        result = response.output["text"]
        if result[0] == "\"" and result[-1] == "\"":
            result = result[1:-1]
        if result[0] == "'" and result[-1] == "'":
            result = result[1:-1]
        return is_success, result

    else:
        print(response.code)  # The error code.
        print(response.message)  # The error message.
        return is_success, response.message


if __name__ == "__main__":
    CorrectEnglishSyntaxAndSpelling(
        "develop version,  unstable control with correct tune centerline fitting.")
